import postcss, {AcceptedPlugin} from 'postcss'
import {AutoAdaptiveConfig} from './AutoAdaptiveConfig'
import JsonUtil from "./JsonUtil";

const defaultConfig: AutoAdaptiveConfig = {
    designWidth: 1920,
    minWidth: 1440,
    minPx: 1
}

const processed = Symbol('processed')

const postcssAutoAdaptive = (options = {}) => {
    const configs: AutoAdaptiveConfig = {...defaultConfig, ...options}

    return {
        postcssPlugin: 'postcss-auto-adaptive',
        Declaration(decl, { Rule, AtRule }) {
            if (!decl[processed]) {
                const values = decl.value.split('px')
                const value = values[0]
                if (values.length > 1 && value > configs.minPx) {
                    // 字体不缩放
                    if (decl.prop === 'font-size') {
                        return
                    }
                    // 得到设计稿下的百分比，*100得到百分比
                    const vwValue = parseFloat(((100 * value) / configs.designWidth).toFixed(3)) + 'vw'
                    // 得到最小尺寸下的px *最小尺寸除以设计尺寸
                    const minPxValue = parseFloat(((value * configs.minWidth) / configs.designWidth).toFixed(3)) + 'px'
                    decl.value = vwValue

                    const mediaDel = decl.clone()
                    mediaDel.value = minPxValue
                    const mediaRule = new Rule({
                        selector: decl.parent.selector, source: decl.source
                    })
                    mediaRule.nodes.push(mediaDel)

                    const mediaAtRule = new AtRule({
                        name: 'media',
                        source: decl.source,
                        params: '(max-width: ' + configs.minWidth + 'px)',
                        nodes: []
                    })
                    mediaAtRule.nodes.push(mediaRule)

                    decl.root().append(mediaAtRule)
                    mediaAtRule[processed] = true
                }
            }
        }
    }
}
postcssAutoAdaptive.postcss = true

// @ts-ignore
postcss([postcssAutoAdaptive]).process(`@media (max-width: 767px) {
        .markdown-body {
            font-size: 15px;
        }
    }`, {from: undefined}).then(res => {
    // console.log(res)
})
